package com.ccx.coachsite.downloadmgr;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.graphics.drawable.Drawable;
import android.util.Log;

import com.ccx.coachsite.data.SystemConst;
import com.ccx.coachsite.util.SUtil;

public class ImageCacheTool {

	private static final String TAG = "ImageCacheTool";
	
	public static String getRealDownUrl(String destUrl){
		if (destUrl.contains(".aspx") || destUrl.contains(".ashx") || destUrl.contains(".jsp")) {
        	//通过重定向获取最终apt、apk、jsp的下载地址并保存在destUrl
			try {
				//destUrl += "&sessionid=" + SessionManage.getSessionId(null);
				HttpParams params = new BasicHttpParams();
				// 设置连接超时和 Socket 超时，以及 Socket 缓存大小
				HttpConnectionParams.setConnectionTimeout(params, SystemConst.CONNECTION_TIMEOUT);
				HttpConnectionParams.setSoTimeout(params, SystemConst.CONNECTION_TIMEOUT);
				HttpConnectionParams.setSocketBufferSize(params, 8192);
				// 设置重定向，缺省为 true
				HttpClientParams.setRedirecting(params, false);
				HttpClient client = new DefaultHttpClient(params);
				destUrl = destUrl.replaceAll(" ", "%20");
				HttpGet request = new HttpGet(destUrl);
				HttpResponse response = client.execute(request);
				Header head = response.getFirstHeader("Location");
				if (head != null) {				
					return head.getValue();
				}
				Log.v(TAG, "down real destUrl="+destUrl);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		
		return destUrl;
	}
	
	/**
 	 * 本地化缓存
 	 * 
 	 * @param url 链接地址
 	 */
 	public static Drawable loadImageFromUrl(String url) {
 		
 		//TODO 判断是否有sdcard,无则直接网络读取返回。
 		String path = url2path(url, SystemConst.DOWNLOAD_DIR);
 		File pic = new File(path);
 		if (!pic.exists()) {
 			if ( !downloadImageByURL(url, path) ) {
 				return null;
 			}
 		}
 		
 		Drawable dw = null;
 		
 		try {
 			dw = Drawable.createFromPath(path);
 		} catch (OutOfMemoryError e) {
			Log.e(TAG, "Out of memory");			
		} catch (Exception e) {
			e.printStackTrace();
		}
 		return dw;
 	}
 	
	public static String url2path (String url, String rootpath){
		if (url==null) return "";
		String rs = rootpath;
		String picname = getPicNameFromUrlWithSuff(url);
		rs = rs+picname;
		rs = SUtil.renameRes(rs);
		return rs;
	}
	
	public static boolean downloadImageByURL(String imgurl, String path) {
		try {
			Log.i(TAG, "downloadImageByurl " + imgurl);
			File f = new File(path);
			if (!f.exists()) {
				URL url = new URL(imgurl);
				URLConnection con = url.openConnection();
				//连接超时时间设置为10秒
				con.setConnectTimeout(SystemConst.CONNECTION_TIMEOUT);
				con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6");
				InputStream is = con.getInputStream();
				if (con.getContentEncoding() != null && con.getContentEncoding().equalsIgnoreCase("gzip")) {
					is = new GZIPInputStream(con.getInputStream());
				}
				byte[] bs = new byte[256];
				int len = -1;
				OutputStream os = new FileOutputStream(f);
				try {
					while ((len = is.read(bs)) != -1) {
						os.write(bs, 0, len);
					}
					// os.flush();
				} finally {
					try {
						os.close();
					} catch (Exception ex) {
					}
					try {
						is.close();
					} catch (Exception ex) {
					}
					os = null;
					is = null;
					con = null;
					url = null;
				}
				return true;
			} else {
				return false;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		} finally {
			
		}
	}
	
	/**
	 * 从图片url中获得图片名
	 * @param url
	 * @return
	 */
	public static String getPicNameFromUrlWithSuff(String url){
		//String str = "http://www.cocplay.com/upload_files/article/2/201003/1_rnazx__12699103296453904.jpg";
		String str = url;
		String [] s = str.split("\\/");
		str = s[s.length-1];
		
		return str; 
	}
	
	/**
	 * 编码图片url中文件名带中文的问题
	 * @param url
	 * @return
	 */
	public static String encodeImgUrl(String url){
		try {
			if(url==null || "".equals(url)){
				return url;
			}			
			
			String imgName = getPicNameFromUrlWithSuff(url);
			String newUrl = url.replace(imgName, "")+URLEncoder.encode(imgName, "utf-8");
			newUrl = newUrl.replaceAll(" ", "%20");
			return newUrl;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return url;
	}
}
